/*
        Copyright (C) 2007  Aaron Defazio

        This program is free software; you can redistribute it and/or
        modify it under the terms of the GNU General Public License
        as published by the Free Software Foundation; either version 2
        of the License, or (at your option) any later version.

        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with this program; if not, write to the Free Software
        Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace AppLn
{
    /// <summary>
    /// Fires an idle event when the user has been idle for a configerable amount of time
    /// </summary>
    class Idle
    {
        #region Interop stuff
        [DllImport("User32.dll")]
        private static extern bool 
                GetLastInputInfo(ref LASTINPUTINFO plii);

        internal struct LASTINPUTINFO 
        {
            public uint cbSize;

            public uint dwTime;
        }
        #endregion

        private uint Interval = 300000;
        private uint IdleInterval = 1200000;
        public event System.EventHandler UserIsIdle;

        private uint GetIdleTime()
        {
            LASTINPUTINFO LastInputInfo = new LASTINPUTINFO();
            LastInputInfo.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(LastInputInfo);
            GetLastInputInfo(ref LastInputInfo);
            return ((uint)Environment.TickCount - LastInputInfo.dwTime);

        }
        /// <summary>
        /// Setup timer 
        /// </summary>
        /// <param name="Interval">How often to check state in miliseconds</param>
        /// <param name="IdleInterval">how long an interval of idleness we consider idle</param>
        public Idle(uint Interval, uint IdleInterval)
        {
            this.Interval = Interval;
            this.IdleInterval = IdleInterval;
            init();
        }
        public Idle()
        {
            init();
        }

        private void init()
        {
            Timer t = new Timer();
            t.Interval = (int)Interval; //1 minute
            t.Tick += new EventHandler(t_Tick);
            t.Start();
        }

        void t_Tick(object sender, EventArgs e)
        {
            if (GetIdleTime() > IdleInterval)
                UserIsIdle(this, new EventArgs());
        }

    }
}
